<template>
  <div class="background">
    <div class="common-layout">
      <el-container>
        <el-header class="header_background">
          <div style="position: absolute; top: 0.1%; left: 2%;">
            <img alt="" src="@/assets/logo1.png" style="width: 40px;">
          </div>
          <div style="position: absolute; top: 1.5%; left: 38%;">
            <span style="font-size: 15px; font-weight: bold; color: whitesmoke">
              您好，用户&nbsp;&nbsp;{{ username }}&nbsp;&nbsp;！欢迎进入房屋租赁平台！
            </span>
          </div>
          <div class="right-info">
            <el-button @click="SignOut" style="margin-right: 10px;">
              <el-icon :size="18" style="margin-right: 5px;">
                <avatar />
              </el-icon>
              退出登录
            </el-button>
          </div>
        </el-header>
        <el-header class="sub_header_background">
          <el-menu
            :default-active="activeIndex"
            router
            class="el-menu-demo"
            mode="horizontal"
            background-color="#545c64"
            text-color="whitesmoke"
            active-text-color="white"
            style="height: 102%;"
            unique-opened
          >
            <el-menu-item index="/tenantHome">首页</el-menu-item>
            <el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
            <el-sub-menu index="transaction">
              <template #title>交易管理</template>
              <el-menu-item index="/TenantApplication">我的申请</el-menu-item>
              <el-menu-item index="/TenantRecord">交易记录</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/SelectHouse">查看房源</el-menu-item>
            <el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
            <el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
            <el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
            <el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
          </el-menu>
        </el-header>
        <el-main>
          <el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
            <h1 style="text-align: center;">RAG问答助手</h1>
            <h2 style="text-align: center;">为您解答关于房源信息的一切问题！</h2>
            <div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
            <div class="chat-container" id="chatContainer"></div>
            <div class="input-area">
              <input type="text" id="questionInput" placeholder="请输入您的问题..." />
              <select id="documentSelect">
                <option value="house1">house1</option>
              </select>
              <select id="chunkTypeSelect">
                <option value="recursive">递归分块</option>
                <option value="semantic">语义分块</option>
              </select>
              <button @click="askQuestion">发送</button>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import request from "@/axios/request";
import request3 from "@/axios/request3";
import request4 from "@/axios/request4";
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      loading: true,
      loadingHouses: false,
      saving: false,
      tenantId: '',
      username: '',
      password: '',
      phone: '',
      email: '',
      selectedHouse: '',
      houseOptions: [],  
      allHouses: [],  
      chunkMethod: '',
      checkMode: '',
      chunkCheckTimer: null,
      summaryData: '',   
      structureData: '',   
      chunkData: '',
      activeIndex: '/PersonalAssistant'
    };
  },
  mounted() {
    this.fetchUserInfo();
    this.loadAllHouses();
    this.loadVectorDatabase();
    
    // 回车键发送
    this.$nextTick(() => {
      const questionInput = document.getElementById('questionInput');
      if (questionInput) {
        questionInput.addEventListener('keypress', (e) => {
          if (e.key === 'Enter') {
            this.askQuestion();
          }
        });
      }
      // 页面加载完成后获取文档列表
      this.loadDocuments();
    });
  },
  beforeUnmount() {
    if (this.chunkCheckTimer) {
      clearInterval(this.chunkCheckTimer);
    }
  },
  methods: {
    async loadAllHouses() {
      this.loadingHouses = true;
      try {
        const res = await request.get("/house/findAll");
        if (res.code === 200) {
          this.allHouses = res.data || [];
          // 初始化时显示所有房源
          this.houseOptions = this.allHouses.map(item => ({
            houseId: item.houseId,
            title: item.title
          }));
        } else {
          ElMessage.error(res.msg || "加载房源数据失败");
        }
      } catch (err) {
        console.error("加载房源数据错误:", err);
        ElMessage.error("网络错误，请稍后再试");
      } finally {
        this.loadingHouses = false;
      }
    },

    async loadVectorDatabase() {
      this.$watch('checkMode', async (newVal) => {
        this.summaryData = '';
        this.structureData = '';
        this.chunkData = '';
        if (newVal === 'summary') {
          try {
            const res = await request3.get('/vector/summary');
            if (res.code === 200) {
              console.log('摘要数据:', res.data);
              this.summaryData = JSON.stringify(res.data, null, 2);
            } else {
              ElMessage.error(res.msg || "获取摘要数据失败");
            }
          } catch (err) {
            console.error("获取摘要数据错误:", err);
            ElMessage.error("网络错误，请稍后再试");
          }
        } else if (newVal === 'structure') {
          try {
            const res = await request3.get('/vector/structure');
            if (res.code === 200) {
              console.log('结构数据:', res.data);
              this.structureData = JSON.stringify(res.data, null, 2);
            } else {
              ElMessage.error(res.msg || "获取结构数据失败");
            }
          } catch (err) {
            console.error("获取结构数据错误:", err);
            ElMessage.error("网络错误，请稍后再试");
          }
        } else if (newVal === 'chunk') {
          this.checkChunkRequirements();
        }
      });

      this.$watch('selectedHouse', () => {
        if (this.checkMode === 'chunk') {
          this.checkChunkRequirements();
        }
      });

      this.$watch('chunkMethod', () => {
        if (this.checkMode === 'chunk') {
          this.checkChunkRequirements();
        }
      });
    },

    async checkChunkRequirements() {
      if (this.chunkCheckTimer) {
        clearInterval(this.chunkCheckTimer);
      }

      const checkAndLoad = async () => {
        if (!this.selectedHouse && this.checkMode === 'chunk') {
          ElMessage.warning("请选择房源");
          return false;
        }

        if (!this.chunkMethod && this.checkMode === 'chunk') {
          ElMessage.warning("请选择分块方式");
          return false;
        }

        try {
          const res = await request3.post('/vector/chunk', {
            params: {
              title: this.selectedHouse,
              chunkMethod: this.chunkMethod
            }
          });
          
          if (res.code === 200) {
            console.log('分块内容数据:', res.data);
            this.chunkData = JSON.stringify(res.data, null, 2);
            if (this.chunkCheckTimer) {
              clearInterval(this.chunkCheckTimer);
              this.chunkCheckTimer = null;
            }
            return true;
          } else {
            ElMessage.error(res.msg || "获取分块内容失败");
            return false;
          }
        } catch (err) {
          console.error("获取分块内容错误:", err);
          ElMessage.error("网络错误，请稍后再试");
          return false;
        }
      };

      const success = await checkAndLoad();
      
      if (!success) {
        this.chunkCheckTimer = setInterval(checkAndLoad, 10000);
      }
    },

    async fetchUserInfo() {
      let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
      if (token && token.tenantId) {
        const tenantId = token.tenantId;
        const res = await request.get(`/tenant/findById/${tenantId}`);
        if (res.code === 200) {
          token = res.data;
        } else {
          ElMessage.error("获取用户信息失败");
        }
        console.log(token);
        if (!token) {
          ElMessage.error("获取用户信息失败");
          console.log("获取用户信息失败");
          return;
        }
        this.tenantId = token.tenantId;
        this.username = token.username;
        this.password = token.password;
        this.phone = token.phone;
        this.email = token.email;
      }
    },
    
    // 搜索房源
    searchHouses(query) {
      if (!query) {
        this.houseOptions = this.allHouses.map(item => ({
          houseId: item.houseId,
          title: item.title
        }));
        return;
      }
      
      const filteredHouses = this.allHouses.filter(item => 
        (item.title).toLowerCase().includes(query.toLowerCase())
      );
      
      this.houseOptions = filteredHouses.map(item => ({
        houseId: item.houseId,
        title: item.title
      }));
    },
    
    // 保存到文件
    async saveToFile() {
      if (!this.selectedHouse && this.checkMode === 'chunk') {
        ElMessage.warning("请选择房源");
        return;
      }
      
      if (!this.chunkMethod && this.checkMode === 'chunk') {
        ElMessage.warning("请选择分块方式");
        return;
      }

      if (!this.checkMode) {
        ElMessage.warning("请选择查看目标");
        return;
      }
      
      this.saving = true;
      try {
        const res = await request4.post('/vector/save', {
          title: this.selectedHouse,
          chunkMethod: this.chunkMethod,
          checkMode: this.checkMode
        });
        
        if (res.code === 200) {
          ElMessage.success("文件保存成功 (保存路径：D:\\Edge下载)");
        } else {
          ElMessage.error(res.msg || "保存失败");
        }
      } catch (err) {
        console.error("保存文件错误:", err);
        ElMessage.error("网络错误，请稍后再试");
      } finally {
        this.saving = false;
      }
    },
    
    SignOut() {
      sessionStorage.clear();
      ElMessage({
        message: '用户退出登录',
        type: 'success',
      });
      this.$router.replace({ path: '/Login' });
    },

    // 显示消息
    showMessage(message, isUser = false) {
      const chatContainer = document.getElementById('chatContainer');
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
      messageDiv.textContent = message;
      chatContainer.appendChild(messageDiv);
      chatContainer.scrollTop = chatContainer.scrollHeight;
    },
    
    // 显示加载状态
    showLoading() {
      const chatContainer = document.getElementById('chatContainer');
      const loadingDiv = document.createElement('div');
      loadingDiv.className = 'message bot-message loading';
      loadingDiv.id = 'loadingMessage';
      loadingDiv.textContent = '正在思考中...';
      chatContainer.appendChild(loadingDiv);
      chatContainer.scrollTop = chatContainer.scrollHeight;
    },
    
    // 隐藏加载状态
    hideLoading() {
      const loadingMessage = document.getElementById('loadingMessage');
      if (loadingMessage) {
        loadingMessage.remove();
      }
    },
    
    // 提问函数
    async askQuestion() {
      const questionInput = document.getElementById('questionInput');
      const documentSelect = document.getElementById('documentSelect');
      const chunkTypeSelect = document.getElementById('chunkTypeSelect');
      
      // 检查元素是否存在
      if (!questionInput || !documentSelect || !chunkTypeSelect) {
        console.error('无法获取输入元素');
        return;
      }
      
      const question = questionInput.value.trim();
      const documentName = documentSelect.value;
      const chunkType = chunkTypeSelect.value;
      
      if (!question) {
        alert('请输入问题');
        return;
      }
      
      // 显示用户问题
      this.showMessage(question, true);
      questionInput.value = '';
      
      // 显示加载状态
      this.showLoading();
      
      try {
        // 发送请求到后端
        const response = await fetch('http://localhost:8084/rag/query', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            question: question,
            document_name: documentName,
            chunk_type: chunkType
          })
        });
        
        const data = await response.json();
        this.hideLoading();
        
        if (data.code === 200) {
          // 显示回答
          this.showMessage(data.data.answer);
          
          // 显示参考资料（简化显示）
          if (data.data.source_documents && data.data.source_documents.length > 0) {
            let sourcesText = "参考资料:\n";
            data.data.source_documents.slice(0, 2).forEach((doc, index) => {
              sourcesText += `${index + 1}. ${doc.content.substring(0, 100)}...\n`;
            });
            this.showMessage(sourcesText);
          }
        } else {
          this.showMessage(`错误: ${data.msg}`);
        }
      } catch (error) {
        this.hideLoading();
        this.showMessage(`网络错误: ${error.message}`);
      }
    },
    
    async loadDocuments() {
      try {
        const response = await fetch('http://localhost:8084/rag/documents');
        const data = await response.json();
        
        if (data.code === 200) {
          const documentSelect = document.getElementById('documentSelect');
          if (documentSelect) {
            documentSelect.innerHTML = '';
            
            data.data.documents.forEach(doc => {
              const option = document.createElement('option');
              option.value = doc.name;
              option.textContent = doc.name;
              documentSelect.appendChild(option);
            });
          }
        }
      } catch (error) {
        console.error('获取文档列表失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.background {
  background-color: whitesmoke;
  height: 100vh;
}

.header_background {
  background-color: #1b4989;
  height: 6vh;
}

.sub_header_background {
  background-color: #545c64;
  height: 7vh;
}

.right-info {
  width: 100px;
  position: absolute;
  right: 2%;
  top: 0.7%
}

.right-info:hover {
  cursor: pointer;
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
  border-color: #409EFF;
}

.line { 
  background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x; 
  height: 0.4rem; 
  flex: 1; 
  background-size: auto;
  margin: 0.16rem;
}

body {
  font-family: Arial, sans-serif;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
.chat-container {
  border: 1px solid #ccc;
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
  background-color: #f9f9f9;
}

.chat-container ::v-deep .message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
  max-width: 80%;
  word-wrap: break-word;
}

.chat-container ::v-deep .user-message {
  background-color: #dcf8c6;
  text-align: right;
  margin-left: auto;
}

.chat-container ::v-deep .bot-message {
  background-color: #f0f0f0;
  border: 1px solid #eee;
  margin-right: auto;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
  max-width: 80%;
  word-wrap: break-word;
}

.user-message {
  background-color: #dcf8c6; 
  text-align: right;
  margin-left: auto; 
}

.bot-message {
  background-color: #f0f0f0;
  border: 1px solid #eee;
  margin-right: auto; 
}

.input-area {
  display: flex;
  gap: 10px;
}

input, select, button {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

input {
  flex-grow: 1;
}

.loading {
  color: #666;
  font-style: italic;
}
</style>